/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.ugame.controller;

import com.google.code.regexp.NamedMatcher;
import com.google.code.regexp.NamedPattern;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.module.Module;
import vn.ugame.module.ModuleFactory;

/**
 *
 * @author namtp
 */
public class Controller extends GenericServlet {

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        ServletContext context = getServletContext();

        String path = request.getRequestURI();

        path = path.replaceAll("/ugame", "");

        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }

        String moduleName = null;
        String urlPattern1 = "/(?<moduleName>[-a-zA-Z0-9]+)/?[\\w\\-\\.,@?^=%&amp;:/~\\+#]*";

        NamedPattern pattern = NamedPattern.compile(urlPattern1);
        NamedMatcher matcher = pattern.matcher(path);
        if (matcher.find()) {
            moduleName = matcher.group("moduleName");
        }

        if (moduleName == null) {
            return;
        }
        request.setAttribute("path", path);

        ModuleFactory moduleFactory = ModuleFactory.createModuleFactory();
        Module module = moduleFactory.createModule(moduleName);

        if (module != null) {
            module.execute(request, response, context);
        }
    }
}
